package com.las.bot.event;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.las.annotation.BotEvent;
import com.las.bot.dao.CqMsgDao;
import com.las.enums.MsgCallBackEnum;
import com.las.strategy.handle.AbstractBotMsgHandler;
import com.model.CqMsg;
import com.utils.ThreadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义消息事件
 */
@BotEvent(event = MsgCallBackEnum.FRIEND_MSG)
public class FriendEvent extends AbstractBotMsgHandler {

    private ThreadPoolExecutor executor = ThreadUtil.getPool();

    @Autowired
    private CqMsgDao cqMsgDao;

    @Override
    public void exec() {
        String data;
        String msgData = getMsgData();
        //执行命令检查私聊图片附带鉴定二字
        JSONArray msgChain = getCqObj().getJSONArray("messageChain");
        if (CollectionUtil.isNotEmpty(msgChain)) {
            Long msgId = null;
            for (int i = 0; i < msgChain.size(); i++) {
                JSONObject jsonObject = msgChain.getJSONObject(i);
                String msgType = jsonObject.getString("type");
                if ("Source".equals(msgType)) {
                    msgId = jsonObject.getLong("id");
                    break;
                }
            }
            if (null != msgId && msgId > 0) {
                for (int j = 0; j < msgChain.size(); j++) {
                    JSONObject jsonObject = msgChain.getJSONObject(j);
                    String msgType = jsonObject.getString("type");
                    if ("Image".equals(msgType)) {
                        msgData = "鉴定";
                        break;
                    }
                }
            }
        }
        if (StrUtil.isBlank(msgData)) {
            return;
        }
        msgData = msgData.trim();
        if (msgData.startsWith("＃")) {
            data = "#" + msgData.substring(1);
        } else {
            data = msgData;
        }
        //执行命令
        exeCommand(data, getUserId(), getId(), getType());
        String finalData = data;
        executor.execute(() -> {
            CqMsg cqMsg = new CqMsg();
            cqMsg.setUserId(getUserId());
            cqMsg.setGroupId(getId());
            cqMsg.setContent(finalData);
            cqMsg.setType(getType());
            cqMsg.setCqData(getCqObj().toJSONString());
            cqMsg.setCreateTime(new Date());
            cqMsgDao.saveOrUpdate(cqMsg);
        });
    }

}
